<template>
	<view class="article-container">
		<!-- 文章标题 -->
		<view class="title">{{ article.title }}</view>

		<!-- 作者信息 -->
		<view class="author-info">
			<!-- <image class="avatar" :src="article.author.avatar" mode="aspectFill"></image> -->
			<view class="author-details">
				<text class="author-name">{{ article.createBy }}</text>
				<text class="publish-time">{{ article.createTime }}</text>
			</view>
		</view>

		<!-- 文章简介 -->
		<!-- <view class="summary">{{ article.brief }}</view> -->

		<!-- 富文本内容 -->
		<rich-text class="content" :nodes="article.content"></rich-text>

		<!-- 统计数据 -->
		<!-- <view class="stats">
      <view class="stat-item">
        <uni-icons type="eye" size="16"></uni-icons>
        <text>{{ article.stats.views }}</text>
      </view>
      <view class="stat-item">
        <uni-icons type="hand-up" size="16"></uni-icons>
        <text>{{ article.stats.likes }}</text>
      </view>
      <view class="stat-item">
        <uni-icons type="chat" size="16"></uni-icons>
        <text>{{ article.stats.comments }}</text>
      </view>
    </view> -->

		<!-- 打赏按钮 -->
		<view class="reward-footer">
			<!-- <button class="reward-btn" @tap="handleReward">打赏作者</button> -->
			<button class="reward-btn" @click="showReward = true">打赏作者</button>
			<!-- <button @click="showReward = true">点击赞赏</button> -->
		</view>

		<!-- 赞赏弹窗遮罩层 -->
		<view v-if="showReward" class="reward-mask" @click="showReward = false">
			<!-- 弹窗内容（阻止遮罩层点击事件冒泡） -->
			<view class="reward-content" @click.stop>
				<view class="reward-title">选择金额，长按识别二维码（或支付宝扫一扫），查看消息</view>
				<!-- 金额选择 -->
				<view class="amount-list">
					<view v-for="(item, index) in amountList" :key="index" class="amount-item" :class="{ active: currentAmount === item.value }" @click="selectAmount(item)">
						{{ item.value }}元
					</view>
				</view>

				<!-- 显示对应图片 -->
				<image v-if="currentImage" :src="currentImage" mode="widthFix" class="reward-image" @longpress="handleLongPress" />

				<!-- 关闭按钮 -->
				<view class="close-btn" @click="showReward = false">×</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getToken
	} from '@/utils/auth'
	import config from '@/config.js'
	import {
		createOrder,
		wapPay
	} from '@/api/cms/cms'
	export default {
		data() {
			return {
				showReward: false, // 控制弹窗显示
				currentAmount: 0, // 当前选中金额
				currentImage: "", // 当前显示图片
				// 金额配置列表（需要替换成你的实际图片路径）
				amountList: [{
						value: 1,
						image: "/static/images/alipay/1.png"
					},
					{
						value: 5,
						image: "/static/images/alipay/5.png"
					},
					{
						value: 10,
						image: "/static/images/alipay/10.png"
					},
					{
						value: 30,
						image: "/static/images/alipay/30.png"
					},
					{
						value: 50,
						image: "/static/images/alipay/50.png"
					},
					{
						value: 99,
						image: "/static/images/alipay/99.png"
					}
				],
				article: {},
				// article: {
				//   title: '如何快速掌握uniapp开发',
				//   author: {
				//     name: '技术达人',
				//     avatar: '/static/default-avatar.png',
				//   },
				//   publishTime: '2023-08-20 10:00',
				//   summary: '本文将从基础到进阶，全面讲解uniapp开发的核心技巧...',
				//   content: `
				//     <div style="color: #333; line-height: 1.6;">
				//       <p>随着跨平台开发需求的增加，uniapp逐渐成为开发者的首选工具...</p>
				//       <img src="/static/article-image.jpg" style="max-width: 100%;">
				//       <p>以下是具体实现步骤：</p>
				//       <!-- 更多富文本内容 -->
				//     </div>
				//   `,
				//   stats: {
				//     views: 2560,
				//     likes: 345,
				//     comments: 89
				//   }
				// }
			}
		},
		onLoad: function(option) {
			// console.log("onLoad")
			// console.log(option.article)
			let articleJson = decodeURIComponent(option.article).replace()
			// 在请求富文本内容后，处理图片路径
			// data.content = data.content.replace(/src="\/(.*?)"/g, 'src="https://你的域名/$1"');
			articleJson = articleJson.replace(/src=\\"\/dev-api\//g, 'src=\\"' + config.baseUrl + '/')
			articleJson = articleJson.replace(/src=\\"\/prod-api\//g, 'src=\\"' + config.baseUrl + '/')
			// console.log("转换后:" + articleJson)
			this.article = JSON.parse(articleJson)
		},
		methods: {
			handleReward() {
				// uni.showActionSheet({
				// 	itemList: ['微信1元打赏', '微信5元打赏', '微信10元打赏', '微信30元打赏', '微信50元打赏', '微信99元打赏'],
				// 	success: (tabIndex) => {
				// 		createOrder(tabIndex).then(res => {
				// 			console.log(res)
				// 				// if (tabIndex == 0)
				// 		})
				// 		const methods = ['wechat', 'alipay']
				// 		uni.showToast({
				// 			title: `即将跳转到${methods[res.tapIndex]}支付`,
				// 			icon: 'none'
				// 		})
				// 	}
				// })
				// if (!getToken()) {
				//   this.$tab.reLaunch('/pages/login')
				// }else{

				// }
			},
			// 选择金额
			selectAmount(item) {
				// #ifdef APP
				createOrder({
					"amount": item.value,
					"articleId": this.article.id
				}).then(res => {
					console.log(res)
					var orderInfo = res.data; //从服务器获取的订单
					uni.getProvider({
						service: 'payment',
						success: function(res) {
							console.log(res.provider)
							if (~res.provider.indexOf('alipay')) {
								uni.requestPayment({
									"provider": "alipay", //固定值为"alipay"
									"orderInfo": orderInfo, //此处为服务器返回的订单信息字符串
									success: function(res) {
										var rawdata = JSON.parse(res.rawdata);
										console.log("支付成功");
									},
									fail: function(err) {
										console.log('支付失败:' + JSON.stringify(err));
									}
								});
							}
						}
					});

				})
				// #endif
				// #ifdef H5
				//下面是网页支付
				// wapPay({
				// 	"amount": item.value,
				// 	"articleId": this.article.id
				// }).then(res => {
				// 	console.log(res)
				// 	var orderInfo = res.data; //从服务器获取的订单// 微信环境跳转处理
				// 	const ua = navigator.userAgent.toLowerCase();
				// 	if (ua.match(/micromessenger/i)) {
				// 		// window.location.href = 'alipays://platformapi/startapp?appId=YOUR_APPID';
				// 		// 或提示用户在浏览器中打开
				// 	} else {
				// 		// 动态创建并提交表单
				// 		const div = document.createElement('div');
				// 		div.innerHTML = orderInfo; // 后端返回的HTML表单字符串
				// 		document.body.appendChild(div);

				// 		this.$nextTick(() => {
				// 			document.forms[0].submit(); // 自动提交表单
				// 		});
				// 	}
				// })
				createOrder({
					"amount": item.value,
					"articleId": this.article.id
				}).then(res => {
					console.log(res)

				})
				this.currentAmount = item.value;
				this.currentImage = item.image;
				// #endif


			},
			handleLongPress() {
				console.log("长安了")
				// this.launchWeChatScan()
				this.saveAndTriggerWeChatScan(); // 保存图片并调起微信扫码  
			},
			async saveAndTriggerWeChatScan() {
				// 网络图片需先下载到本地  
				const localPath = aplus.io.convertLocalFileSystemURL(this.currentImage);
				console.log(this.currentImage)
				console.log(localPath)

				uni.saveImageToPhotosAlbum({
					filePath: localPath,
					success: () => {
						this.launchWeChatScan(); // 调起微信扫码  
					},
					fail: () => {
						uni.showToast({
							title: '保存失败，请手动保存后扫码',
							icon: 'none'
						});
					}
				});
			},
			launchWeChatScan() {
				// #ifdef APP-PLUS  
				plus.runtime.launchApplication({
					action: 'weixin://scanqrcode',
					error: (e) => {
						uni.showToast({
							title: '未安装微信',
							icon: 'none'
						});
					}
				});
				// #endif  
			}




		}
	}
</script>

<style lang="less" scoped>
	.article-container {
		padding: 24rpx 32rpx;
		background-color: #fff;
	}

	.title {
		font-size: 40rpx;
		font-weight: bold;
		line-height: 1.4;
		margin-bottom: 24rpx;
	}

	.author-info {
		display: flex;
		align-items: center;
		margin-bottom: 32rpx;

		.avatar {
			width: 80rpx;
			height: 80rpx;
			border-radius: 50%;
			margin-right: 20rpx;
		}

		.author-details {
			display: flex;
			flex-direction: column;

			.author-name {
				font-size: 28rpx;
				color: #333;
			}

			.publish-time {
				font-size: 24rpx;
				color: #999;
			}
		}
	}

	.summary {
		padding: 20rpx;
		background-color: #f8f8f8;
		border-radius: 8rpx;
		color: #666;
		font-style: italic;
		margin-bottom: 32rpx;
	}

	.content {
		line-height: 1.8;
		font-size: 30rpx;
		color: #333;
		margin-bottom: 40rpx;

		/deep/ img {
			max-width: 100%;
			margin: 20rpx 0;
			border-radius: 8rpx;
		}
	}

	.stats {
		display: flex;
		justify-content: space-around;
		padding: 24rpx 0;
		border-top: 1rpx solid #eee;
		border-bottom: 1rpx solid #eee;
		margin: 40rpx 0;

		.stat-item {
			display: flex;
			align-items: center;
			color: #666;

			text {
				margin-left: 10rpx;
			}
		}
	}

	.reward-footer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background: #fff;
		padding: 20rpx;
		box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.05);

		.reward-btn {
			background-color: #ff4c4c;
			color: #fff;
			border-radius: 50rpx;
			font-size: 32rpx;

			&::after {
				border: none;
			}
		}
	}



	/* 遮罩层样式 */
	.reward-mask {
		padding: 30rpx;
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.6);
		display: flex;
		justify-content: center;
		align-items: center;
		z-index: 999;
	}

	/* 弹窗内容 */
	.reward-content {
		background: #fff;
		border-radius: 20rpx;
		padding: 40rpx;
		position: relative;
		width: 90%;
	}

	.reward-title {
		margin: 20rpx 0rpx;
		color: firebrick;
	}

	/* 金额列表样式 */
	.amount-list {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
		margin-bottom: 30rpx;
	}

	/* 金额列表样式 */
	.amount-list {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
		margin-bottom: 30rpx;
	}

	.amount-item {
		flex: 1;
		min-width: 30%;
		padding: 20rpx;
		text-align: center;
		border: 1px solid #eee;
		border-radius: 10rpx;
		transition: all 0.3s;
	}

	.amount-item.active {
		background: #ffd700;
		border-color: #ffd700;
		font-weight: bold;
	}

	/* 赞赏图片样式 */
	.reward-image {
		width: 100%;
		max-height: 60vh;
		margin-top: 20rpx;
	}

	/* 关闭按钮 */
	.close-btn {
		position: absolute;
		top: -40rpx;
		right: -40rpx;
		width: 60rpx;
		height: 60rpx;
		border-radius: 50%;
		background: #fff;
		color: #333;
		font-size: 50rpx;
		text-align: center;
		line-height: 55rpx;
	}
</style>